<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="() => { searchData= {} }">
        <jeepay-text-up v-model:value="searchData['agentNo']" :placeholder="'代理商号'" />
        <jeepay-text-up v-model:value="searchData['pid']" :placeholder="'上级代理商号'" />
        <jeepay-text-up v-model:value="searchData['isvNo']" :placeholder="'服务商号'" />
        <jeepay-text-up v-model:value="searchData['agentName']" :placeholder="'代理商名称'" />
        <jeepay-text-up v-model:value="searchData['loginUsername']" :placeholder="'代理商登录名'" />
        <jeepay-text-up v-model:value="searchData['contactTel']" :placeholder="'手机号'" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="searchData['state']" placeholder="代理商状态">
            <a-select-option value="">
              全部
            </a-select-option>
            <a-select-option value="0">
              禁用
            </a-select-option>
            <a-select-option value="1">
              启用
            </a-select-option>
            <a-select-option value="2">
              审核中
            </a-select-option>
          </a-select>
        </a-form-item>
        <jeepay-text-up v-model:value="searchData['balanceAmount']" :placeholder="'钱包余额'" />
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="searchData"
        row-key="agentNo"
        :statisticsIsShow="$access('ENT_AGENT_INFO_COUNT')"
        @btnLoadClose="btnLoading=false"
      >
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in tableCount" :key="index" class="item">
              <div v-if="item.type == 'line'" class="line" />
              <div class="title">{{ item.title }}</div>
              <div v-if="item.title" class="amount" :style="{color: item.textColor}">
                <span class="amount-num">{{ item.content }}</span>
                <span v-if="item.isAmount">元</span>
              </div>
            </div>
          </div>
        </template>
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_AGENT_INFO_ADD')" type="primary" @click="addFunc">
            <plus-outlined />新建
          </a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'agentName'">
            <a @click="detailFunc(record.agentNo)"><b>{{ record.agentName }}</b></a>
          </template>

          <template v-if="column.key === 'balanceAmount'">
            <a @click="historyFunc(record.agentNo, 1)"><b>{{ (typeof record.balanceAmount == 'number' && typeof record.unAmount == 'number') ? ('￥' + (record.balanceAmount - record.unAmount) / 100) : '无账户' }}</b></a>
          </template>

          <template v-if="column.key === 'auditProfitAmount'">
            <a @click="historyFunc(record.agentNo, 2)"><b>{{ typeof record.auditProfitAmount == 'number'? ('￥' + record.auditProfitAmount / 100) : '无账户' }}</b></a>
          </template>

          <template v-if="column.key === 'unAmount'">
            <b>{{ typeof record.unAmount == 'number'? ('￥' + record.unAmount / 100) : '无账户' }}</b>
          </template>

          <template v-if="column.key === 'freezeAmount'">
            <b>{{ typeof record.freezeAmount == 'number'? ('￥' + record.freezeAmount / 100) : '无账户' }}</b>
          </template>

          <template v-if="column.key === 'state'">
            <a-badge 
              :status="record.state === 0?'error':record.state === 1?'processing':record.state === 2?'warning':record.state === 3?'error':'yellow'" 
              :text="record.state === 0?'禁用':record.state === 1?'启用':record.state === 2?'审核中':record.state === 3?'审核驳回':'未认证'" 
            />
          </template>

          <template v-if="column.key === 'operation'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_AGENT_INFO_EDIT') && (record.state === 0 || record.state === 1)" type="link" @click="editFunc(record.agentNo)">修改</a-button>
              <a-button v-if="$access('ENT_AGENT_INFO_AUDIT') && (record.state === 2 || record.state === 3)" type="link" @click="auditAgentInfo(record.agentNo)">审核</a-button>
              <a-button v-if="$access('ENT_AGENT_RATE_CONFIG')" type="link" @click="showFeeConfigList(record.agentNo)">费率配置</a-button>
              <a-button v-if="$access('ENT_AGENT_CONFIG_PAGE')" type="link" @click="agentConfigFunc(record.agentNo)">高级功能配置</a-button>
              <a-button v-if="$access('ENT_AGENT_BALANCE_CHANGE')" type="link" @click="changeBalanceFunc(record.agentNo)">调账</a-button>
              <a-button v-if="$access('ENT_AGENT_INFO_DEL')" type="link" style="color: red" @click="delFunc(record.agentNo)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>
    <!-- 新增页面组件  -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callback-func="searchFunc" />
    <!-- 审核代理商  -->
    <AuditInfo ref="auditInfo" :callback-func="searchFunc" />
    <!-- 详情页面组件  -->
    <InfoDetail ref="infoDetail" :callback-func="searchFunc" />

    <!-- 调账  -->
    <ChangeBalance ref="changeBalanceRef" :callback-func="searchFunc" />

    <!-- 流水记录 -->
    <HistoryPanelDrawer ref="historyPanelDrawerRef" />

    <!-- 费率配置页面  -->
    <JeepayPayConfigDrawer ref="jeepayPayConfigDrawerRef" configMode="mgrAgent" />

    <!-- 代理商高级配置  -->
    <AgentConfig ref="agentConfigRef" />
  </page-header-wrapper>
</template>
<script setup lang="ts">

import { API_URL_AGENT_LIST, req, reqLoad, $agentInfoCount } from '@/api/manage'
import InfoAddOrEdit from './AddOrEdit.vue'
import InfoDetail from './Detail.vue'
import ChangeBalance from './ChangeBalance.vue'
import AuditInfo from './AuditInfo.vue'
import HistoryPanelDrawer from '@/views/order/history/HistoryPanelDrawer.vue'
import AgentConfig from './AgentConfig.vue'

import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
const { $infoBox,$access } = getCurrentInstance()!.appContext.config.globalProperties

const infoDetail = ref()
const infoAddOrEdit = ref()
const changeBalanceRef = ref()
const auditInfo = ref()
const infoTable = ref()
const agentConfigRef = ref()
const historyPanelDrawerRef = ref()
let tableCount:any = ref([]) // 数据统计数组

const jeepayPayConfigDrawerRef = ref()
let tableColumns = reactive([
  { key: 'agentName', title: '代理商名称',  fixed: 'left'},
  { key: 'agentNo', title: '代理商号', dataIndex: 'agentNo' },
  { key: 'contactTel', title: '手机号', dataIndex: 'contactTel' },
  { key: 'level', title: '等级', dataIndex: 'level' },
  { key: 'pid', title: '上级代理', dataIndex: 'pid' },
  { key: 'isvNo', title: '服务商号', dataIndex: 'isvNo' },
  { key: 'balanceAmount', title: '钱包余额' },
  { key: 'auditProfitAmount', title: '在途利润' },
  { key: 'unAmount', title: '提现中金额' },
  { key: 'freezeAmount', title: '冻结金额' },
  { key: 'state', title: '状态' },
  { key: 'createdAt', title: '创建日期', dataIndex: 'createdAt' },
  { key: 'operation', title: '操作', fixed: 'right', align: 'center'}
])

  let btnLoading = ref(false)
  let searchData : any = ref({})

    // 请求table接口数据
  function reqTableDataFunc(params: any) {
    return req.list(API_URL_AGENT_LIST, params)
  }

  onMounted( () => {
    getTableCount()
  })

  // 数据统计
  const getTableCount = () => {

    if(!$access('ENT_AGENT_INFO_COUNT')){
      return false
    }

    $agentInfoCount(searchData.value).then( res => {
      tableCount.value = [ 
        {title: '代理总数', symbol: 'add', isAmount: false, content: res.totalAgent},
        {type: 'line'},
        {title: '钱包余额', symbol: 'add', isAmount: true, textColor: '#1A66FF', content: (res.balanceAmount / 100).toFixed(2)},
        {type: 'line'},
        {title: '在途利润', symbol: 'add', isAmount: true, textColor: '#1A66FF', content: (res.auditProfitAmount / 100).toFixed(2)},
        {type: 'line'},
        {title: '提现中金额', symbol: 'add', isAmount: true, textColor: '#1A66FF', content: (res.unAmount / 100).toFixed(2)},
        {type: 'line'},
        {title: '冻结金额', symbol: 'add', isAmount: true, textColor: '#1A66FF', content: (res.freezeAmount / 100).toFixed(2)},
      ]
    })
  }

  function searchFunc () { // 点击【查询】按钮点击事件
    // 金额校验
    if (searchData.value['balanceAmount']) {
      const regex = /^(([1-9]{1}\d{0,6})|(0{1}))(\.\d{1,2})?$/
      if (!regex.test(searchData.value['balanceAmount'])) {
        return $infoBox.message.error('请输入正确的金额')
      }
    }

    getTableCount()

    infoTable.value.refTable(true)
  }

  function addFunc () { // 业务通用【新增】 函数
    infoAddOrEdit.value.show()
  }

  function editFunc (recordId: any) { // 业务通用【修改】 函数
    infoAddOrEdit.value.show(recordId)
  }

  function auditAgentInfo (recordId: any) { // 审核代理商
    auditInfo.value.show(recordId)
  }

  function detailFunc (recordId: any) { // 代理商详情页
    infoDetail.value.show(recordId)
  }

  function changeBalanceFunc (recordId: any) { // 调账
    changeBalanceRef.value.show(recordId)
  }

    // 删除代理商
  function delFunc (recordId: any) {
    $infoBox.confirmDanger('确认删除？', '该操作将删除代理商下所有配置及用户信息', () => {
        reqLoad.delById(API_URL_AGENT_LIST, recordId).then((res: any) => {
          infoTable.value.refTable(true)
          $infoBox.message.success('删除成功')
        })
    })
  }

  function showFeeConfigList (recordId) { // 费率配置
    jeepayPayConfigDrawerRef.value.show(recordId)
  }


  function historyFunc(recordId, opAccountType){

    let queryObject = { infoType: 'AGENT', infoId: recordId, opAccountType : opAccountType }  
    historyPanelDrawerRef.value.show(queryObject, false)

  }

  function agentConfigFunc (recordId: any) { // 配置 函数
    agentConfigRef.value.show(recordId)
  }

</script>
